import { Inject, Injectable, OnModuleInit } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { PageQuery } from "src/common/page/PageQuery";
import { Result } from "src/common/Result";
import { ObjectUtils } from "src/common/utils/ObjectUtils";
import config from "src/config";
import { Type } from "src/entity/Type";
import { INIT_CONSTANTS } from "src/InitProjectConstant";
import { Repository } from "typeorm";

@Injectable()
export class TypeService implements OnModuleInit{
    
    @InjectRepository(Type)
    private typeRepsitory: Repository<Type>;

    /**
     * 初始化
     */
    async onModuleInit() {
        if (!config.doInit) {
            return;
        }
        let list: Type[] = [];
        for (let item of INIT_CONSTANTS.type.list) {
            let type = new Type();
            ObjectUtils.copyProperties(item, type);
            list.push(type);
        }
        try {
            await this.typeRepsitory.save(list);
            console.log("初始化种类成功!");
            
        } catch (error) {
            console.log("初始化种类失败...");
        }
    }

    /**
     * 种类列表查询
     * @param query 
     * @returns 
     */
    async selectTypeList(query: PageQuery<Type>) {
        let queryBuilder = this.typeRepsitory.createQueryBuilder("t");
        let param = query.param;
        if (param?.typeName) {
            queryBuilder.andWhere(`t.type_name  = '${param?.typeName}'`)
        }
        return await PageQuery.getManyAndCount(query, queryBuilder);
    }


    /**
     * 添加种类
     * @param type 
     */
    async addType(type: Type) {
        let one = await this.typeRepsitory.findOneBy({typeName: type.typeName});
        if (one) {
            return Result.failed("该种类已存在!");
        }
        await this.typeRepsitory.save(type);
        return Result.success();
    }

    /**
     * 编辑种类
     * @param type 
     */
    async update(type: Type) {
        let oneName = await this.typeRepsitory.findOneBy({typeName: type.typeName});
        if (oneName && oneName.typeId != type.typeId) {
            return Result.failed("该种类已存在!");
        }
        // let one = await this.typeRepsitory.findOneBy({typeId: type.typeId});
        await this.typeRepsitory.update(type.typeId, type);
        return Result.success();
    }
}